﻿using FangDuShi_API.Common.DEncrypt;
using Microsoft.AspNet.SignalR;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;

namespace FangDuShi_API.Controllers
{
    public class ApiController : Controller
    {
        //
        // GET: /Api/
        /// <summary>
        /// API逻辑类
        /// </summary>
        private BLL.API apiBLL = new BLL.API();
        /// <summary>
        /// 错误消息定义
        /// </summary>
        private UniValidate uniValidate = new UniValidate();
        /// <summary>
        /// 经纪人BLL
        /// </summary>
        private BLL.Realtor realtorBLL = new BLL.Realtor();
        /// <summary>
        /// 经纪人操作日志BLL
        /// </summary>
        private BLL.RealtorLog realtorLogBLL = new BLL.RealtorLog();
        /// <summary>
        /// 房源采集BLL
        /// </summary>
        private BLL.HouseSrcInfoWebDC houseSrcInfoWebDCBLL = new BLL.HouseSrcInfoWebDC();

        public string APIMethod(string postData)
        {
            string returnMsg = "";
            JObject msgJson = JObject.Parse(postData);
            string method = msgJson["method"].ToString();
            string msg = msgJson["msg"].ToString();
            switch (method)
            {
                case "DBConnectTest":
                    {
                        returnMsg = DBConnectTest();
                        break;
                    }
                case "Login":
                    {
                        returnMsg = Login(msg);
                        break;
                    }
                case "GetFAppVer":
                    {
                        returnMsg = GetFAppVer();
                        break;
                    }
                case "GetServerDatetime":
                    {
                        returnMsg = GetServerDatetime();
                        break;
                    }
            }

            return returnMsg;
        }

        /// <summary>
        /// 获取数据库服务器系统时间
        /// </summary>
        /// <returns></returns>
        private string GetServerDatetime()
        {
            string returnMsg = "";
            string logid = OperateSession.get(GlobalConstant.PARAM_REALTOR_ID);
            if (string.IsNullOrEmpty(logid))
            {
                returnMsg = uniValidate.UserIsNotLogin();
            }
            else
            {
                JObject jObject = new JObject();
                jObject["ServerDatetime"] =apiBLL.GetServerDatetime().ToString("yyyy-MM-dd HH:mm:ss");
                returnMsg = uniValidate.NoError(jObject.ToString());
            }
            return returnMsg;
        }

        /// 测试数据库连接是否成功
        /// </summary>
        /// <returns></returns>
        private string DBConnectTest()
        {
            string returnMsg = "";
            int result = apiBLL.DBConnectTest();
            if (result == -1)
            {
                returnMsg = uniValidate.DbConnectError();
            }
            else
            {
                returnMsg = uniValidate.NoError();
            }
            return returnMsg;
        }

        /// <summary>
        /// 用户登录
        /// </summary>
        /// <param name="logID"></param>
        /// <returns></returns>
        private string Login(string loginString)
        {
            string returnMsg = "";
            bool isSuccess = false;
            //解密数据包
            try
            {
                loginString = DESEncrypt.Decrypt(loginString, GlobalConstant.GLOBAL_ENCRYPTVALUE);
                JObject msgJson = JObject.Parse(loginString);
                string logid = msgJson["logid"].ToString();
                string password = msgJson["password"].ToString();

                bool hasPrvUser = realtorBLL.ExistsMobile(logid);
                decimal realtorID = 0;
                if (hasPrvUser)
                {

#if DEBUG
                    //DEBUG模式
                    object mode = msgJson["mode"];
                    if (mode != null && mode.ToString() == "DEBUG")
                    {
                        string userName = realtorBLL.GetRealName(logid);
                        realtorID = realtorBLL.GetRealtorID(logid);
                        JObject jObject = new JObject();
                        jObject["FLogID"] = realtorID;
                        jObject["FUserName"] = userName;

                        returnMsg = uniValidate.NoError(jObject.ToString());
                        isSuccess = true;
                    }
                    else
                    {
                        returnMsg = uniValidate.BcsError();
                    }
#else
                    //验证密码
                    string dataPassword = realtorBLL.GetUserPassword(logid);
                    string outString = FormsAuthentication.HashPasswordForStoringInConfigFile(logid + password, "MD5");
                    if (outString.ToLower() != dataPassword.ToLower())
                    {
                        returnMsg = uniValidate.UserPasswordError();
                    }
                    else
                    {
                        string userName = realtorBLL.GetRealName(logid);
                        realtorID = realtorBLL.GetRealtorID(logid);;
                        JObject jObject = new JObject();
                        jObject["FLogID"] = realtorID;
                        jObject["FUserName"] = userName;

                        returnMsg = uniValidate.NoError(jObject.ToString());
                        isSuccess = true;
                    }
#endif
                    if (isSuccess)
                    {
                        OperateSession.add(GlobalConstant.PARAM_REALTOR_ID, realtorID.ToString());//把登陆ID保存到Session
                        //添加登录日志
                        AddRealtorLog(realtorID, "登录成功");

                    }

                }
                else
                {
                    returnMsg = uniValidate.UserNotExists();
                }



            }
            catch
            {
                returnMsg = uniValidate.ParamError();
            }
            return returnMsg;

        }
        /// <summary>
        /// 保存经纪人操作日志
        /// </summary>
        private void AddRealtorLog(decimal realtorID,string content)
        {
            try
            {
                Model.RealtorLog realtorLogModel = new Model.RealtorLog();
                Model.Realtor realtorModel = realtorBLL.GetModel(realtorID);
                if (realtorModel != null)
                {
                    realtorLogModel.FAgencyBranchID = realtorModel.FAgencyBranchID;
                    realtorLogModel.FContent = content;
                    realtorLogModel.FDate = DateTime.Now;
                    realtorLogModel.FDistrictNo = realtorModel.FDistrictNo;
                    realtorLogModel.FIP = Common.GenerateUtil.GetClientIPv4Address();
                    realtorLogModel.FMobile = realtorModel.FMobile;
                    realtorLogModel.FRealName = realtorModel.FRealName;
                    realtorLogModel.FRealtorID = realtorID;
                    realtorLogModel.FURL = Request.Url.AbsolutePath;
                    realtorLogBLL.Add(realtorLogModel);
                }
            }
            catch
            {
            }

        }
        /// <summary>
        /// 获取房秘书版本号
        /// </summary>
        /// <returns></returns>
        private string GetFAppVer()
        {
            string returnMsg = "";
            string logid = OperateSession.get(GlobalConstant.PARAM_REALTOR_ID);
            if (string.IsNullOrEmpty(logid))
            {
                returnMsg = uniValidate.UserIsNotLogin();
            }
            else
            {
                string strFAppVer = System.Configuration.ConfigurationManager.AppSettings["FAppVer"];

                if (string.IsNullOrEmpty(strFAppVer))
                {
                    returnMsg = uniValidate.BcsError();
                }
                else
                {
                    JObject jObject = new JObject();
                    jObject["FAppVer"] = strFAppVer;
                    returnMsg = uniValidate.NoError(jObject.ToString());
                }
            }
            return returnMsg;
        }

        /// <summary>
        /// 房屋采集信息
        /// </summary>
        /// <returns></returns>
        private string GetHouseCollect(string tableName, string fields, int pageSize, int pageIndex, string strWhere, string fOrderFiled, int orderType)
        {
            string returnMsg = "";
            int total = 0;

            try
            {
                DataSet ds= apiBLL.GetListByPage(tableName, fields, pageSize, pageIndex, strWhere, fOrderFiled, orderType, out total);
                List<Model.HouseSrcInfoWebDC> HouseSrcInfoWebDCList = houseSrcInfoWebDCBLL.DataTableToList(ds.Tables[0]);
                string JsonHouseSrc = JsonConvert.SerializeObject(HouseSrcInfoWebDCList);


                JObject jObject = new JObject();
                jObject["HouseCollectList"] = "";
                returnMsg = uniValidate.NoError(jObject.ToString());
            }
            catch
            {
                returnMsg = uniValidate.DbQueryError();
            }
            return returnMsg;
        }


	}
}